package cn.tedu.csmall.product.ex.handler;

import cn.tedu.csmall.product.ex.ServiceCode;
import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.nio.file.AccessDeniedException;
import java.util.List;
import java.util.Set;

@Slf4j
@RestControllerAdvice

public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult<Void> handleServiceException(ServiceException e){
        log.debug("处理ServiceException，serviceCode={},message={}",e.getServiceCode(),e.getMessage());
        return JsonResult.fail(e);
    }

    @ExceptionHandler
    public JsonResult<Void> handleServiceException(BindException e){
        log.debug("BindException");

        List<FieldError> fieldErrors = e.getFieldErrors();

        StringBuilder messageBuilder=new StringBuilder();
        for (FieldError fieldError:fieldErrors) {
            messageBuilder.append(fieldError.getDefaultMessage()+"!");
        }

        return JsonResult.fail(ServiceCode.ERR_BAN_REQUEST.getValue(),messageBuilder.toString());
    }

    @ExceptionHandler
    public JsonResult<Void> handleServiceException(ConstraintViolationException e){
        log.debug("ConstraintViolationException");

        Integer serviceCode=ServiceCode.ERR_BAN_REQUEST.getValue();
        StringBuilder messageBuilder=new StringBuilder();

        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
       for(ConstraintViolation<?> constraintViolation:constraintViolations){
           messageBuilder.append(constraintViolation.getMessage());
       }
       String message=messageBuilder.toString();
        return JsonResult.fail(serviceCode,message);
    }

    @ExceptionHandler
    public JsonResult<Void> handleAccessDeniedException(AccessDeniedException e){
        log.debug("处理AccessDeniedException异常");
        Integer serviceCode = ServiceCode.ERR_UNAUTHORIZED_DISABLED.getValue();
        String message = "操作失败，账号无此操作权限！";
        return JsonResult.fail(serviceCode, message);
    }

    @ExceptionHandler
    public JsonResult<Void> handleThrowable(Throwable e){
        log.debug("处理Throwable异常");
        e.printStackTrace();

        Integer serviceCode=99999;
        String message="程序运行过程中出现未知错误，请联系管理员处理！";

        return JsonResult.fail(serviceCode,message);
    }
}


